package start.demo01.xml.domain;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParseXml {
	public static List<Book> parseXml(InputStream is) throws Exception, SAXException{
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		BookHandler handler = new BookHandler();
		parser.parse(is, handler);
		return handler.getBooks();
	}

	private static class BookHandler extends DefaultHandler{
		private List<Book> books;
		private Book book;
		private String tag;
		@Override
		public void startDocument() throws SAXException {
			books = new ArrayList<Book>();
		}

		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes)
				throws SAXException {
			if("book".equals(qName)) {
				book = new Book();
				book.setId(Integer.valueOf(attributes.getValue("id")));
			}
			tag = qName;
			
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			if("book".equals(qName)) {
				books.add(book);
			}
			tag = null;
		}

		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
			if(tag != null) {
				String data = new String(ch,start,length);
				if("name".equals(tag))book.setName(data);
				else if("author".equals(tag))book.setAuthor(data);
				else if("publisher".equals(tag))book.setPublisher(data);
				else if("price".equals(tag))book.setPrice(Float.parseFloat(data));
			}
			
		}

		public List<Book> getBooks() {
			return books;
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		BufferedInputStream is = new BufferedInputStream(new FileInputStream("books.xml"));
		parseXml(is).forEach(System.out::println);
		
	}
}
